import { Injectable, Req } from "@nestjs/common";
import { UsersService } from "../users/users.service";
import { JwtService } from "@nestjs/jwt";
import { AccountEntity } from "../users/entity/account.entity";
import { GetCaptchaDto } from "./dto/get-captcha.dto";


@Injectable()
export class AuthService {
  constructor(private readonly usersService: UsersService, private readonly jwtService: JwtService) {
  }

  //验证用户名和密码是否通过
  async validateUser(account: string, password: string): Promise<any> {
    const _account = new AccountEntity();
    _account.account = account;
    _account.password = password;
    const accountRes = await this.usersService.accountFind(_account);
    if (accountRes) {
      return accountRes;
    }
    return null;
  }

  // 验证通过，生成token返回给客户端
  async login(account: AccountEntity, res) {
    const payload = { account: account.account, id: account.id };
    res.set({ "Authorization": "Bearer " + this.jwtService.sign(payload) });
    res.send({access_token: this.jwtService.sign(payload)});
    return {
      access_token: this.jwtService.sign(payload)
    };
  }

  // 获取验证码
  getCaptcha(dto: GetCaptchaDto, @Req() request) {
    const svgCaptcha = require("svg-captcha");
    const c = svgCaptcha.create({
      size: 4,
      width: dto.width ? dto.width : 150,
      height: dto.height ? dto.height : 45
    });
    request.session.captcha = c.text;
    request.session.cookie.maxAge = 300000;
    return c.data;
  }

  //验证验证码
  async VerifyCaptcha(captchaCode: string, @Req() request) {
    return request.session.captcha === captchaCode;
  }
}